package com.olive.service.impl;


import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.olive.dto.JwtUserDto;
import com.olive.entity.Authority;
import com.olive.entity.Role;
import com.olive.entity.User;
import com.olive.mapper.AuthorityMapper;
import com.olive.service.RoleService;
import com.olive.service.UserService;

import cn.hutool.core.util.StrUtil;

@Service
public class SmsUserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private UserService userService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private AuthorityMapper authorityMapper;


	@Override
	public UserDetails loadUserByUsername(String mobile) throws UsernameNotFoundException {
		// 根据手机号获取用户
		User user = userService.findByMobile(mobile);
		if (user == null){
			throw new UsernameNotFoundException("该手机号对应的用户不存在");
		}
		List<Role> roles = roleService.loadRolesByUsername(user.getUsername());
		Set<String> roleInfos = roles.stream().map(Role::getRoleName).collect(Collectors.toSet());
		List<Authority> authorities = authorityMapper.loadPermissionByRoleCode(roleInfos);
		List<String> authorityNames = authorities.stream().map(Authority::getAuthorityName).filter(StrUtil::isNotEmpty).collect(Collectors.toList());
		authorityNames.addAll(roleInfos.stream().map(roleName->"ROLE_"+roleName).collect(Collectors.toList()));
		return new JwtUserDto(user, new HashSet<>(roles), authorityNames);
	}
}


